<?php

class PricetypesReceptionsController extends AppController {

    var $name = 'PricetypesReceptions';

    function index() {
        $this->PricetypesReception->Pricetype->recursive = 0;
        $pricetypes = $this->PricetypesReception->Pricetype->find('all', array('conditions'=>array('Pricetype.deleted'=>0),'order'=>array('Pricetype.name'=>'ASC')));
        $this->set('pricetypes', $pricetypes);

        if (!empty($this->data)) {

            $array_datos = $this->data['PricetypesReception'];

            //empiezo una transaccion
            $this->PricetypesReception->query('SET AUTOCOMMIT = 0;');
            $this->PricetypesReception->query('START TRANSACTION;');
            $bandera = true; //la uso para ver si algo salio mal
            //borro de la tabla pricetypes_receptions
            if (!$this->PricetypesReception->deleteAll(array('1=1'), false, false)) {
                $bandera = false;
            }

            //ahora recorro los datos y voy guardando
            foreach ($pricetypes as $tipo_precio) {
                $array_guardar = array();
                $array_guardar['pricetype_id'] = $tipo_precio['Pricetype']['id'];
                $array_guardar['client_cost'] = $array_datos['client_cost_' . $tipo_precio['Pricetype']['id']];
                $array_guardar['employee_cost'] = $array_datos['employee_cost_' . $tipo_precio['Pricetype']['id']];
                
//                pr($array_guardar);
//                die;
                $this->PricetypesReception->create();
                if (!$this->PricetypesReception->save($array_guardar)) {
                    $bandera = false;
                }
            }
            
            if ($bandera) {
                $this->Session->setFlash('Se ha guardado la configuración de los precios');
                $this->PricetypesReception->query('COMMIT;');
                $this->PricetypesReception->query('SET AUTOCOMMIT = 1;');
                $this->redirect(array('controller' => 'pricetypes_receptions', 'action' => 'index'));
            } else {
                $this->Session->setFlash('La configuración no ha sido guardada. Por favor, intente nuevamente.');
                $this->PricetypesReception->query('ROLLBACK;');
                $this->PricetypesReception->query('SET AUTOCOMMIT = 1;');
            }
            
        } else {
            //si no vino nada, me cargo todo en el $this->data para que se levante solo
            $res = $this->PricetypesReception->find('all');
            foreach ($res as $tipo) {
                $this->data['PricetypesReception']['client_cost_' . $tipo['PricetypesReception']['pricetype_id']] = $tipo['PricetypesReception']['client_cost'];
                $this->data['PricetypesReception']['employee_cost_' . $tipo['PricetypesReception']['pricetype_id']] = $tipo['PricetypesReception']['employee_cost'];
            }
        }
    }

}
